// var script = document.createElement('script');
// script.src = "../static/js/jquery-1.8.2.min.js";
// document.head.appendChild(script);

/**
 * 添加购物车
 * @param id
 * @param userId
 */
function addCartByParam(id, userId, number) {

    //判断是否是未登陆状态
    if (userId == 0) {

        cocoMessage.info('请先登陆，在加入购物车！')
        return;
    }
    jQuery.ajax({
        url: 'car/joinShopping',
        data: {
            id: id,
            number: number
        },
        dataType: 'json',
        method: 'post',
        success: function (data) {

            if (data.status == 1) {

                cocoMessage.info(data.message);

                //渲染购物车方法
                apply(data);

            } else {
                cocoMessage.info(data.message);
            }
        }

    })

}

/**
 * 渲染购物车方法
 */
function apply(data) {

    jQuery("#number").empty();//清空购物车数量
    jQuery("#ul").empty();  //清空
    jQuery("#sumPrice").empty()   //清空总价格
    jQuery("#stock").empty();    //清空库存
    var str = '';//拼接
    var sumPrice = 0;//总金额

    //渲染购物车
    for (var i = 0; i < data.order.length; i++) {

        var order = data.order[i];

        console.log(order)

        str += "<li><div class='img'><a href=" + 'car/product?id=' + order.productId + "><img src=" + 'upload/' + order.images + " width='58' height='58' /></a>" +
            "</div><div class='name'><a href='#'>" + order.name + "</a></div><div class='price'>" +
            "<font color='#ff4e00'>￥" + order.price + "</font>&nbsp;&nbsp;  <span>X" + order.number + "</span></div></li>";

        sumPrice += order.sumPrice;

    }

    jQuery("#ul").append(str);  //拼接代码
    jQuery("#sumPrice").text(sumPrice);  //赋值总金额
    jQuery("#number").text(data.order.length); //赋值数量
    jQuery("#stock").append(data.product != null ? data.product.stock : 0);  //赋值库存


}

/**
 * 添加购物车方法
 * @param id
 * @param userId
 */
function addShoppping(id, userId) {

    //获取数量
    var number = document.getElementById("productNumber").value;

    if (isNaN(number)) {
        cocoMessage.info("数量必须为数字！");
        jQuery("#productNumber").val(1);

    } else if (number.length >= 10) {
        cocoMessage.info("数量太大，添加购物车失败！");
        jQuery("#productNumber").val(1);
    } else if (number > 0) {

        //添加购物车方法
        addCartByParam(id, userId, number);

    } else {

        cocoMessage.info("数量不能小于1");
        jQuery("#productNumber").val(1);

    }


}

/**
 * 加、减
 * @param type
 */
function subtract(type, obj, id) {

    //判断是减
    if (type == 0) {

        var number = jQuery(obj).next().val();

        //判断减到1到时，就不能减法了
        if (number > 1) {

            jQuery(obj).next().val('');

            jQuery(obj).next().val(Number(number) - 1);

            //结算方法
            subtractNumber(obj, id, Number(number) - 1, "-");

        } else {

            cocoMessage.info("在减商品就没了")

        }

        //判断是加时
    } else {

        var number = jQuery(obj).prev().val();

        jQuery(obj).prev().val('');

        jQuery(obj).prev().val(Number(number) + 1);

        //结算方法
        subtractNumber(obj, id, Number(number) + 1, "+");

    }


}

/**
 * 结算方法
 */
function subtractNumber(obj, id, number, type) {

    jQuery.ajax({
        url: "car/updateNumber",
        method: "post",
        data: {
            id: id,
            number: number,
            type: type
        },
        dataType: "json",
        success: function (data) {

            if (data.status == 1) {

                cocoMessage.info(data.message);

                //渲染购物车方法
                apply(data);
                applyProduct(data);
            } else {
                cocoMessage.info(data.message);

                if (type == "-") {
                    jQuery(obj).next().val(Number(number) + 1);
                } else {
                    jQuery(obj).prev().val(Number(number) - 1);
                }


            }

        }


    })

}

/**
 * 渲染商品
 */
function applyProduct(data) {

    //清空body
    jQuery("#body").empty();
    jQuery("#sumProductPrice").empty();//清空总金额


    var str = "";//拼接

    var sumPrice = 0;//总金额

    //渲染购物车
    for (var i = 0; i < data.order.length; i++) {

        var order = data.order[i];

        str += "<tr><td><div class='c_s_img'><img src=" + 'upload/' + order.images + " width='73' height='73' /></div>" +
            "<span>" + order.name + "</span></td><td align='center'>" + '￥' + order.price + "</td><td align='center'>" +
            "<div class='c_num'><input type='button' onclick='subtract(0,this," + order.id + ")' class='car_btn_1' />" +
            "<input type='text' disabled value=" + order.number + " onchange='subtractNumber(32,this)' name=''  class='car_ipt' />" +
            "<input type='button' onclick='subtract(1,this," + order.id + ")' class='car_btn_2' /></div>" +
            "</td><td align='center' style='color:#ff4e00;'>" + '￥' + order.sumPrice + "</td><td align='center'>" +
            "<a onclick='deleteByCar(" + order.id + ")'>删除</a>&nbsp;</td></tr>";

        sumPrice += order.sumPrice;//总金额

    }

    jQuery("#body").append(str);  //渲染商品
    jQuery("#sumProductPrice").append("￥" + sumPrice == 0 ? 0 : sumPrice);  //渲染总金额


    if (data.order.length == 0) {
        jQuery("#empty").empty();
    }

}

/**
 * 删除购物车方法
 */
function deleteByCar(id) {

    jQuery.ajax({
        url: "car/deleteByCar",
        method: "post",
        data: {
            id: id
        },
        dataType: "json",
        success: function (data) {

            //判断删除成功时
            if (data.status == 1) {

                cocoMessage.info(data.message);

                //渲染方法
                applyProduct(data);
                apply(data);//渲染购物车
            } else {

                cocoMessage.info(data.message);

            }

        }


    })

}


/**
 * 结算 订单支付提醒
 */
function settlement3() {
    //判断地址
    var addressId = jQuery("input[name='selectAddress']:checked").val();
    var newAddress = jQuery("input[name='address']").val();
    var newRemark = jQuery("input[name='remark']").val();
    if (addressId == "" || addressId == null) {
        cocoMessage.info("请选择收货地址");
        return;
    } else if (addressId == "-1") {
        if (newAddress == "" || newAddress == null) {
            cocoMessage.info("请填写新的收货地址");

            return;
        } else if (newAddress.length <= 2 || newAddress.length >= 50) {
            cocoMessage.info("收货地址为2-50个字符");

            return;
        } else if (newRemark == "" || newRemark == null) {
            cocoMessage.info("请填写新备注");
            return;
        } else if (newRemark.length <= 2 || newRemark.length >= 50) {
            cocoMessage.info("备注为2-50个字符");
            return;
        }
    }
    jQuery.ajax({
        url: "address/addAddress",
        method: "post",
        data: {
            addressId: addressId,
            address: newAddress,
            remark: newRemark
        },
        success: function (data) {

            //判断成功时
            if (data.status == 1) {
                cocoMessage.info(data.message);

                window.setTimeout("window.location='address/skip'", 1000);

            } else {

                cocoMessage.info(data.message);
            }

        }
    });
}

/**
 * 登陆验证
 */
function logVerify() {

    //获取用户名
    var name = jQuery("input[name='loginName'").val();

    //获取密码
    var password = jQuery("input[name='password']").val();

    //判断用户名或密码为空时
    if (name == null || name == '') {

        cocoMessage.info("用户名不能为空！");

    } else if (password == null || password == '') {

        cocoMessage.info("密码不能为空！");

    } else {


        jQuery.ajax({
            url: "user/log",
            method: "post",
            data: {
                loginName: name,
                password: password
            },
            dataType: "json",
            success: function (data) {

                //成功时
                if (data.status == 1) {

                    cocoMessage.info(data.message);

                    window.setTimeout("window.location='user/initIndex'", 1000);

                    //用户名或密码错误
                } else {
                    cocoMessage.info(data.message);

                }

            }


        })

    }

}

